const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
// 日志 将koa原生的logger换成 封装的log4js
// const logger = require('koa-logger')
const log4js = require('./utils/log4js')
const Route_index = require('./routes/index')
const koaJwt = require('koa-jwt')
const util = require('./utils/util')
require('./config/db')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
// app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))



// logger
app.use(async (ctx, next) => {
  // const start = new Date()
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
  await next().catch(err=>{
    if(err.status=='401'){
      ctx.status = 200
      ctx.body = util.fail('Token认证失败','',util.CODE.AUTH_ERROR)
    }else{
      throw err
    }
  })
  // log4js.info('Some info message')
  // const ms = new Date() - start
  // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 检验Token
/**
 * token检验不通过就会将status转换为401，
 * 需要在其发生前将next绑定catch错误处理，将status进行修改
 */
app.use(koaJwt({secret:'iloveu'}).unless({
  path:[/^\/api\/users\/login/]
}))


// routes
// app.use(index.routes(), index.allowedMethods())
app.use(Route_index.routes(), Route_index.allowedMethods())



// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
  log4js.error(err.stack)
});

module.exports = app
